﻿using DotNetCore.CAP;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace VIP.Events
{
    public class EventSender : IEventSender
    {
        private readonly ICapPublisher _capBus;

        public EventSender(ICapPublisher capBus)
        {
            _capBus = capBus;
        }
        public Task SendAsync<T>(T data, string name = null) where T : IVIPEvent
        {
            var tp = data.GetType();

            if (String.IsNullOrEmpty(name))
            {
                var attrs = tp.GetCustomAttributes(typeof(EventPropertyAttribute), false);
                if (attrs.Length > 0)
                {
                    name = ((EventPropertyAttribute)attrs[0]).Name;
                }
            }
            if (String.IsNullOrEmpty(name))
            {
                name = typeof(T).Name;
            }
            return this._capBus.PublishAsync(name, data);
        }
    }
}
